package wht.jly.forum.utils.validatecode.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import wht.jly.forum.utils.validatecode.controller.ImageValidateCodeController;
import wht.jly.forum.utils.validatecode.exception.ImageValidateCodeException;
import wht.jly.forum.utils.validatecode.image.ImageValidateCode;
import wht.jly.forum.utils.validatecode.properties.ImageValidateCodeProperties;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 向 spring security 中添加 校验验证码过滤器
 * <p>
 * 继承 OncePerRequestFilter工具类，保证每次请求只被执行一次
 *
 * @author lanyangji
 * @date 2019/2/19 15:08
 */
public class ImageValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 默认要拦截的登录请求URL
     */
    private static final String LOGIN_URL = "/login";

    /**
     * 校验码自定义配置类
     */
    private ImageValidateCodeProperties imageValidateCodeProperties;

    /**
     * 认证失败处理器
     */
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 存储系统默认的，以及用户配置的拦截的URL的集合
     */
    private Set<String> urls = new HashSet<>();

    /**
     * url匹配工具类
     */
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(imageValidateCodeProperties.getUrl(), ",");
        Arrays.stream(configUrls).forEach(urls::add);
        // 一定要加入系统默认的登录页
        urls.add(LOGIN_URL);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /**
         * 判断该请求是否要被拦截
         */
        boolean isIntercepted = false;
        for (String url : urls) {
            if (antPathMatcher.match(url, request.getRequestURI())) {
                isIntercepted = true;
                break;
            }
        }

        if (isIntercepted) {
            try {
                validate(new ServletWebRequest(request));
            } catch (ImageValidateCodeException e) {
                // 捕获到的 验证码校验失败异常，交给 authenticationFailureHandler处理
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }

        // 如果不是要拦截的请求，或者校验通过，直接放行
        filterChain.doFilter(request, response);
    }

    /**
     * 校验验证码
     *
     * @param servletWebRequest
     */
    private void validate(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
        // 从session中取出 imageValidateCode
        ImageValidateCode codeInSession = (ImageValidateCode) servletWebRequest.getRequest()
                .getSession().getAttribute(ImageValidateCodeController.SESSION_KEY_IMAGE_VALIDATE_CODE);

        // 获取请求中的校验码
        String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "validateCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ImageValidateCodeException("验证码不能为空");
        }

        if (codeInSession == null) {
            throw new ImageValidateCodeException("验证码不存在");
        }

        if (codeInSession.isExpired()) {
            throw new ImageValidateCodeException("验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ImageValidateCodeException("验证码不匹配");
        }

        // 校验完成后，从session中移除 imageValidateCode
        servletWebRequest.getRequest().getSession().removeAttribute(ImageValidateCodeController.SESSION_KEY_IMAGE_VALIDATE_CODE);
    }

    /**
     * getter、 setter
     *
     * ....
     *
     * @return
     */
    public ImageValidateCodeProperties getImageValidateCodeProperties() {
        return imageValidateCodeProperties;
    }

    public void setImageValidateCodeProperties(ImageValidateCodeProperties imageValidateCodeProperties) {
        this.imageValidateCodeProperties = imageValidateCodeProperties;
    }

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    public ImageValidateCodeFilter() {
    }

    public ImageValidateCodeFilter(ImageValidateCodeProperties imageValidateCodeProperties, AuthenticationFailureHandler authenticationFailureHandler) {
        this.imageValidateCodeProperties = imageValidateCodeProperties;
        this.authenticationFailureHandler = authenticationFailureHandler;
    }
}
